<?php
/**
 * WordPress Spider Monitor - 安全许可证服务器
 * 
 * 此文件部署在您的服务器上，负责验证客户端许可证
 * 客户端无法修改此代码，确保授权安全
 */

class Spider_License_Server {
    
    private $database;
    private $server_secret = 'your-server-secret-key'; // 服务器密钥
    
    public function __construct() {
        $this->init_database();
    }
    
    /**
     * 初始化数据库连接
     */
    private function init_database() {
        // 连接您的许可证数据库
        $this->database = new PDO(
            'mysql:host=localhost;dbname=license_db',
            'username',
            'password'
        );
    }
    
    /**
     * 验证许可证
     */
    public function verify_license($request_data) {
        // 验证请求签名
        if (!$this->verify_request_signature($request_data)) {
            return $this->create_response(false, '请求签名验证失败');
        }
        
        $license_key = $request_data['license_key'];
        $domain = $request_data['domain'];
        $user_id = $request_data['user_id'];
        
        // 查询数据库中的许可证信息
        $stmt = $this->database->prepare("
            SELECT * FROM licenses 
            WHERE license_key = ? AND status = 'active'
        ");
        $stmt->execute([$license_key]);
        $license = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$license) {
            return $this->create_response(false, '无效的许可证密钥');
        }
        
        // 检查许可证是否过期
        if ($license['expires_at'] && strtotime($license['expires_at']) < time()) {
            return $this->create_response(false, '许可证已过期');
        }
        
        // 检查域名绑定
        if ($license['domain'] && $license['domain'] !== $domain) {
            return $this->create_response(false, '许可证域名不匹配');
        }
        
        // 检查使用次数限制
        if ($license['max_activations'] > 0) {
            $stmt = $this->database->prepare("
                SELECT COUNT(*) FROM license_activations 
                WHERE license_key = ? AND status = 'active'
            ");
            $stmt->execute([$license_key]);
            $activation_count = $stmt->fetchColumn();
            
            if ($activation_count >= $license['max_activations']) {
                return $this->create_response(false, '许可证激活次数已达上限');
            }
        }
        
        // 记录激活信息
        $this->record_activation($license_key, $domain, $user_id);
        
        // 返回许可证信息
        return $this->create_response(true, '许可证验证成功', array(
            'features' => $this->get_license_features($license['plan']),
            'periods' => $this->get_license_periods($license['plan']),
            'expires_at' => $license['expires_at'],
            'plan' => $license['plan']
        ));
    }
    
    /**
     * 获取许可证功能列表
     */
    private function get_license_features($plan) {
        $features = array(
            'basic' => array('trend_chart', 'top_spiders'),
            'pro' => array('trend_chart', 'top_spiders', 'access_paths', 'article_crawl', 'ip_segments', 'path_stats', 'article_stats'),
            'enterprise' => array('trend_chart', 'top_spiders', 'access_paths', 'article_crawl', 'ip_segments', 'path_stats', 'article_stats', 'advanced_analytics', 'api_access')
        );
        
        return $features[$plan] ?? $features['basic'];
    }
    
    /**
     * 获取许可证时间范围权限
     */
    private function get_license_periods($plan) {
        $periods = array(
            'basic' => array('today', 'yesterday'),
            'pro' => array('today', 'yesterday', 'week', 'month'),
            'enterprise' => array('today', 'yesterday', 'week', 'month', 'year')
        );
        
        return $periods[$plan] ?? $periods['basic'];
    }
    
    /**
     * 记录激活信息
     */
    private function record_activation($license_key, $domain, $user_id) {
        $stmt = $this->database->prepare("
            INSERT INTO license_activations (license_key, domain, user_id, activated_at, status)
            VALUES (?, ?, ?, NOW(), 'active')
            ON DUPLICATE KEY UPDATE 
            last_used = NOW(), status = 'active'
        ");
        $stmt->execute([$license_key, $domain, $user_id]);
    }
    
    /**
     * 验证请求签名
     */
    private function verify_request_signature($request_data) {
        if (!isset($request_data['signature'])) {
            return false;
        }
        
        $expected_signature = hash_hmac('sha256', 
            $request_data['license_key'] . $request_data['domain'] . $request_data['user_id'] . $request_data['timestamp'],
            $this->server_secret
        );
        
        return hash_equals($expected_signature, $request_data['signature']);
    }
    
    /**
     * 创建响应
     */
    private function create_response($valid, $message, $data = array()) {
        $response = array(
            'valid' => $valid,
            'message' => $message,
            'data' => $data,
            'timestamp' => time()
        );
        
        // 添加服务器签名
        $response['signature'] = hash_hmac('sha256', 
            json_encode($data), 
            $this->server_secret
        );
        
        return $response;
    }
}

// API 端点处理
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        http_response_code(400);
        echo json_encode(array('error' => 'Invalid JSON'));
        exit;
    }
    
    $server = new Spider_License_Server();
    
    if (isset($_GET['action']) && $_GET['action'] === 'verify') {
        $result = $server->verify_license($input);
        echo json_encode($result);
    } else {
        http_response_code(404);
        echo json_encode(array('error' => 'Action not found'));
    }
} else {
    http_response_code(405);
    echo json_encode(array('error' => 'Method not allowed'));
}
